<?php

namespace app\controller;

//好友控制器
use app\service\UserFriendService;
use support\Response;
use think\Exception;
use think\facade\Db;


class  UserFriendController extends Base
{

    //获取陌生人列表
    public function stranger_list(): Response
    {
        $limit = $this->request->get('limit', 10);
        $res = (new UserFriendService())->stranger_list($this->user_id, $limit);
        return json($res);
    }


    //获取好友列表
    public function ship_list(): Response
    {
        $limit = $this->request->get('limit', 10);
        $res = (new UserFriendService())->ship_list($this->user_id, $limit);
        return json($res);
    }

    //好友请求列表
    public function request_list()
    {
        $limit = $this->request->get('limit', 10);
        $res = (new UserFriendService())->request_list($this->user_id, $limit);
        return json($res);
    }



    //好友绑定关系
    public function bind_ship()
    {
        $answer = $this->request->post('answer');
        //好友id
        $friend_id = $this->request->post('friend_id');
        if ($friend_id == 0) {
            return json(apiError('参数错误'));
        }

        $res = (new UserFriendService())->bind_ship($this->user_id,$friend_id,$answer);
        return json($res);
    }


    //搜索好友
    public function search(): Response
    {
        $limit = $this->request->get('limit', 10);
        $keyword = $this->request->get('keyword', '');
        if ($keyword == '') {
            return json(apiError('请输入搜索关键字'));
        }
        $res = (new UserFriendService())->search($this->user_id, $keyword, $limit);
        return json($res);
    }

    //添加好友
    public function add()
    {
        $receiver_id = $this->request->post('receiver_id', 0);
        $remarks = $this->request->post('remarks', '加个好友吧');
        if ($receiver_id == 0) {
            return json(apiError('参数错误'));
        }
        try {
            Db::startTrans();
            $res = (new UserFriendService())->add($this->user_id, $receiver_id, $remarks);
            if ($res['code'] == 0) {
                Db::rollBack();
            } else {
                Db::commit();
            }
        } catch (Exception $e) {
            Db::rollBack();
            throw $e;
        }

        return json($res);
    }

    //验证好友
    public function verify(): Response
    {
        $id = $this->request->post('id', 0);
        $state = $this->request->post('state', 0);
        if ($id == 0) {
            return json(apiError('参数错误'));
        }
        Db::startTrans();
        try {
            $res = (new UserFriendService())->verify($this->user_id, $id, $state);
            if ($res['code'] == 0) {
                Db::rollBack();
            } else {
                Db::commit();
            }
        } catch (Exception $e) {
            Db::rollBack();
            throw $e;
        }
        return json($res);

    }




}
